package net.midnighttd.engine.entity;

import net.midnighttd.engine.view.sprite.*;
import net.midnighttd.engine.Engine;
import org.w3c.dom.Element;
import java.awt.*;

/**
 * Author: Adam Scarr
 * Date: 19/04/2009
 * Time: 6:47:04 PM
 *
 * An entity is the base of all objects in the game.
 */
public class Entity {
    protected String name;
    protected Sprite sprite;
    protected String type;
    private int x, y;
    protected boolean active = false;
    protected Engine engine;
    private String description;

    /**
     * Creates a copy of the given entity.
     * @param entity    Entity to copy from.
     */
    public Entity(Entity entity) {
        name = entity.name;
        engine = entity.engine;
        sprite = engine.getSpriteManager().getSprite(entity.sprite.getName());
        type = entity.type;
        description = entity.description;
    }

    public Entity(Engine game, SpriteManager sm, Element element) {
        name = element.getAttribute("name");
        sprite = sm.getTemplateSprite(element.getAttribute("sprite"));
        description = element.getTextContent().trim();
        this.engine = game;
        type = "entity";
    }

    public boolean isPassable() {
        return true;
    }

    public void setActive(boolean v) {
        this.active = v;
    }

    public String getName() {
        return name;
    }

    public void draw(Graphics g) {
        if(active) {
            sprite.draw(g);
            drawEntity(g);
        }
    }

    public String getDescription() {
        return description;
    }

    public void gameLogic() {
        sprite.update();
    }

    public void drawEntity(Graphics g) {
        
    }

    public void setLocation(int x, int y) {
        int oldX = this.x;
        int oldY = this.y;
        this.x = x;
        this.y = y;
        Dimension tile = engine.getMapManager().getTileSize();
        sprite.setLocation(x * tile.width, y * tile.height);

        engine.getEntityManager().updateActiveEnt(this, oldX,  oldY);
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Entity getDuplicate() {
        return new Entity(this);
    }

    public double getDistanceTo(Entity e) {
        int x = e.getX() - getX();
        int y = e.getY() - getY();
        return Math.sqrt(x*x + y*y);
    }

    public Sprite getSprite() {
        return sprite;
    }

    public boolean isActive() {
        return active;
    }

    public String getType() {
        return type;
    }

    public Image getImage() {
        return sprite.toImage();
    }
}
